<template>
  <div class="address-page">
    <NavBar>
      <template #default>
        收货地址
      </template>
      <template #right>
        <el-button type="text" @click="handleAddAddress">新增地址</el-button>
      </template>
    </NavBar>

    <div class="address-container">
      <!-- 地址列表 -->
      <div v-if="!loading && addressList.length > 0" class="address-list">
        <div
          v-for="address in addressList"
          :key="address.addressId"
          class="address-item"
          :class="{ 'default-address': address.isDefault }"
        >
          <div class="address-content" @click="handleEditAddress(address)">
            <div class="address-header">
              <span class="receiver">{{ address.receiverName }}</span>
              <span class="phone">{{ address.receiverMobile }}</span>
              <el-tag v-if="address.isDefault" size="small" type="danger">默认</el-tag>
            </div>
            <div class="address-detail">
              {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}
            </div>
          </div>
          <div class="address-actions">
            <el-checkbox
              v-model="address.isDefault"
              :true-label="1"
              :false-label="0"
              @change="() => handleSetDefault(address.addressId)"
            >
              设为默认
            </el-checkbox>
            <el-button
              type="danger"
              link
              @click.stop="handleDeleteAddress(address.addressId)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-address">
        <el-empty description="暂无收货地址">
          <el-button type="primary" @click="handleAddAddress">新增地址</el-button>
        </el-empty>
      </div>

      <!-- 加载状态 -->
      <div v-else class="loading-address">
        <el-skeleton :rows="3" animated />
      </div>
    </div>

    <!-- 新增/编辑地址对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑地址' : '新增地址'"
      width="90%"
      :close-on-click-modal="false"
      @closed="resetForm"
    >
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="收货人" prop="receiverName">
          <el-input
            v-model="addressForm.receiverName"
            placeholder="请输入收货人姓名"
            @input="handleInput('receiverName')"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号" prop="receiverMobile">
          <el-input
            v-model="addressForm.receiverMobile"
            placeholder="请输入手机号"
            @input="handleInput('receiverMobile')"
            clearable
          />
        </el-form-item>
        <el-form-item label="所在地区" prop="areaText">
          <el-input
            v-model="addressForm.areaText"
            readonly
            placeholder="请选择省市区"
            @click="showAreaPicker = true"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input
            v-model="addressForm.detailAddress"
            type="textarea"
            placeholder="请输入详细地址"
            rows="2"
            @input="handleInput('detailAddress')"
            clearable
          />
        </el-form-item>
        <el-form-item label="设为默认" prop="isDefault">
          <el-switch v-model="addressForm.isDefault" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddressForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 全屏地区选择器 -->
    <el-drawer
      v-model="showAreaPicker"
      title="选择地区"
      direction="btt"
      size="80%"
      :close-on-click-modal="false"
    >
      <div class="area-picker-container">
        <el-cascader-panel
          v-model="addressForm.selectedArea"
          :options="areaOptions"
          :props="{
            expandTrigger: 'hover',
            label: 'name',
            value: 'code',
            children: 'children'
          }"
          @change="handleAreaChange"
        />
        <div class="area-picker-footer">
          <el-button @click="showAreaPicker = false">取消</el-button>
          <el-button type="primary" @click="confirmAreaSelection">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import NavBar from '@/components/common/NavBar.vue'
import { useAddressStore } from '@/stores/addressStore'
import { useUserStore } from '@/stores/userStore'
import { getDistrict } from '@/api/amap'

const userStore = useUserStore()
const addressStore = useAddressStore()

// 初始化地址数据
onMounted(async () => {
  if (userStore.isLogin) {
    await Promise.all([
      addressStore.initAddresses(),
      loadAreaData()
    ])
  }
})

// 计算属性
const addressList = computed(() => addressStore.addressList)
const loading = computed(() => addressStore.loading)

// 对话框相关
const dialogVisible = ref(false)
const showAreaPicker = ref(false)
const isEdit = ref(false)
const addressForm = ref(initEmptyForm())
const addressFormRef = ref(null)

// 初始化空表单
function initEmptyForm() {
  return {
    addressId: null,
    receiverName: '',
    receiverMobile: '',
    selectedArea: [],
    areaText: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    isDefault: false
  }
}

// 地区数据
const areaOptions = ref([])

// 表单验证规则
const rules = {
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: ['blur', 'input'] },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: ['blur', 'input'] }
  ],
  receiverMobile: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'input'] },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: ['blur', 'input']
    }
  ],
  areaText: [
    { required: true, message: '请选择所在地区', trigger: 'blur' }
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: ['blur', 'input'] },
    { min: 5, max: 60, message: '长度在 5 到 60 个字符', trigger: ['blur', 'input'] }
  ]
}

// 处理输入事件 - 清除单个字段的验证状态
const handleInput = (fieldName) => {
  addressFormRef.value?.clearValidate(fieldName)
}

// 处理添加地址
const handleAddAddress = () => {
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录')
    return
  }
  resetForm()
  isEdit.value = false
  dialogVisible.value = true
}

// 处理编辑地址
const handleEditAddress = async (address) => {
  resetForm()
  isEdit.value = true

  // 深拷贝地址数据避免污染原数据
  addressForm.value = {
    ...JSON.parse(JSON.stringify(address)),
    isDefault: address.isDefault === 1
  }

  // 设置地区选择器需要的格式
  if (address.province && address.city && address.district) {
    addressForm.value.areaText = `${address.province} ${address.city} ${address.district}`
  }

  dialogVisible.value = true
  await nextTick()
  addressFormRef.value?.clearValidate()
}

// 重置表单
const resetForm = () => {
  addressForm.value = initEmptyForm()
  addressFormRef.value?.resetFields()
}

// 加载地区数据
const loadAreaData = async () => {
  try {
    const response = await getDistrict('中国', 3)
    if (response.data?.districts?.[0]?.districts) {
      areaOptions.value = transformDistrictData(response.data.districts[0].districts)
    }
  } catch (error) {
    console.error('加载地区数据失败:', error)
    ElMessage.error('加载地区数据失败')
  }
}

// 转换地区数据格式
const transformDistrictData = (districts) => {
  return districts?.map(item => ({
    name: item.name,
    code: item.adcode,
    level: item.level,
    children: item.districts ? transformDistrictData(item.districts) : []
  })) || []
}

// 确认地区选择
const confirmAreaSelection = () => {
  if (addressForm.value.selectedArea.length === 3) {
    const [provinceCode, cityCode, districtCode] = addressForm.value.selectedArea

    const findArea = (areas, code) =>
      areas.find(area => area.code === code)

    const province = findArea(areaOptions.value, provinceCode)?.name || ''
    const city = findArea(findArea(areaOptions.value, provinceCode)?.children || [], cityCode)?.name || ''
    const district = findArea(
      findArea(
        findArea(areaOptions.value, provinceCode)?.children || [],
        cityCode
      )?.children || [],
      districtCode
    )?.name || ''

    addressForm.value = {
      ...addressForm.value,
      areaText: `${province} ${city} ${district}`,
      province,
      city,
      district
    }
  }
  showAreaPicker.value = false
}

// 提交地址表单
const submitAddressForm = async () => {
  try {
    // 验证表单
    await addressFormRef.value.validate()

    // 验证地区选择
    if (!addressForm.value.province || !addressForm.value.city || !addressForm.value.district) {
      ElMessage.error('请选择完整的省市区')
      return
    }

    // 准备提交数据
    const addressDTO = {
      ...(isEdit.value && { addressId: addressForm.value.addressId }),
      receiverName: addressForm.value.receiverName.trim(),
      receiverMobile: addressForm.value.receiverMobile.trim(),
      province: addressForm.value.province,
      city: addressForm.value.city,
      district: addressForm.value.district,
      detailAddress: addressForm.value.detailAddress.trim(),
      isDefault: addressForm.value.isDefault ? 1 : 0,
      userId: userStore.userAccount.userId
    }

    // 根据模式调用不同方法
    if (isEdit.value) {
      await addressStore.updateAddress(addressDTO)
      ElMessage.success('地址更新成功')
    } else {
      await addressStore.addAddress(addressDTO)
      ElMessage.success('地址添加成功')
    }

    // 关闭对话框并刷新列表
    dialogVisible.value = false
    await addressStore.initAddresses()
  } catch (error) {
    console.error('提交地址表单失败:', error)
    if (error?.message) {
      ElMessage.error(error.message)
    }
  }
}

// 设置默认地址
const handleSetDefault = async (addressId) => {
  try {
    await addressStore.setDefaultAddress(addressId)
    ElMessage.success('默认地址设置成功')
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error(error.message || '设置默认地址失败')
  }
}

// 删除地址
const handleDeleteAddress = async (addressId) => {
  try {
    await ElMessageBox.confirm('确定要删除该地址吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await addressStore.deleteAddress(addressId)
    ElMessage.success('地址删除成功')
    await addressStore.initAddresses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
      ElMessage.error(error.message || '删除地址失败')
    }
  }
}
</script>

<style scoped>
.address-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.address-container {
  padding: 10px;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.address-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.default-address {
  border-left: 3px solid #ff5000;
}

.address-content {
  margin-bottom: 15px;
  cursor: pointer;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 16px;
}

.receiver {
  font-weight: bold;
  margin-right: 15px;
}

.phone {
  margin-right: 15px;
  color: #666;
}

.address-detail {
  color: #666;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px dashed #eee;
}

.empty-address {
  margin-top: 50px;
}

.loading-address {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.area-picker-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.area-picker-footer {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eee;
}

:deep(.el-cascader-panel) {
  flex: 1;
  border: none;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

:deep(.el-drawer__body) {
  padding: 0;
  display: flex;
  flex-direction: column;
}
</style>